package server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author songyi
 * @date 2020/6/28 0028 15:26
 * @description
 */
public class StaticResourceUtil {

    // 根据url，获取静态资源的绝对路径
    public static String getAbsolutePath(String url) {
        String rootPath = StaticResourceUtil.class.getResource("/").getPath();
        return rootPath.replaceAll("\\\\", "/") + url;
    }

    // 读取静态资源文件输入流，通过输出流输出
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = fileInputStream.available();
        }
        // 输出http请求头，再输出具体内容
        outputStream.write(HttpProtocoUtil.getHeader200(count).getBytes());
        // 已经读取的内容长度
        long written = 0;
        // 计划每次缓冲的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        while (written < count) {
            if (written + byteSize > count) { // 剩余未读取大小不足一个1024长度，那就按真实长度处理
                // 剩余的文件长度
                byteSize = (int) (count - written);
                bytes = new byte[byteSize];
            }
            fileInputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }
    }


}
